﻿using System;
using System.Reflection;
using static System.Console;

public class MyFieldClassA
{
    public string Field = "A Field";
}

public class MyFieldClassB
{
    private string field = "B Field";
    public string Field
    {
        get
        {
            return field;
        }
        set
        {
            if (field!=value)
            {
                field=value;
            }
        }
    }
}


class Program
{
    class People
    {
        public required string name;
        public int age;

        public int Age
        {
            get
            {
                return age;
            }
        }
    }
    public static void Main()
    {
        var people = new People
        {
            name = "Hello",
            age = 18
        };

        TestReflect(people, "name");
        TestReflect(people, "age");
        TestReflect(people, "Age");

        MyFieldClassB myFieldObjectB = new();
        MyFieldClassA myFieldObjectA = new();

        Type myTypeA = typeof(MyFieldClassA);
        FieldInfo? myFieldInfo = myTypeA.GetField("Field");

        Type myTypeB = typeof(MyFieldClassB);
        FieldInfo? myFieldInfo1 = myTypeB.GetField("field",
            BindingFlags.NonPublic | BindingFlags.Instance);

        Console.WriteLine("The value of the public field is: '{0}'",
            myFieldInfo?.GetValue(myFieldObjectA));
        Console.WriteLine("The value of the private field is: '{0}'",
            myFieldInfo1?.GetValue(myFieldObjectB));
    }

    public static void TestReflect(object target, string fieldName)
    {
        bool hasFind = false;
        Type type = target.GetType();
        foreach (PropertyInfo propertyInfo in type.GetProperties())
        {
            if (propertyInfo.Name == fieldName)
            {
                hasFind = true;
                break;
            }
        }

        if (!hasFind)
        {
            foreach (FieldInfo fieldInfo in type.GetFields())
            {
                if (fieldInfo.Name == fieldName)
                {
                    hasFind = true;
                    break;
                }
            }
        }
        Console.WriteLine($"{fieldName} is {(hasFind ? "hasFind" : "notFind")}");
    }
}